<?php

namespace Fluency;

/**
 * Renders values using views.
 * 
 * @package Fluency
 * @author  Ignas Rudaitis
 * @version 2.0.0
 */
class Renderer
{
    const CONTENT_PARAMETER_NAME = "content";

    private $viewLoader;

    public function __construct($viewLoader)
    {
        if (!is_callable($viewLoader)) {
            throw new \BadFunctionCallException("The view loader is not callable");
        }
        $this->viewLoader = $viewLoader;
    }

    private function applyView($viewName, array $params = array())
    {
        $view = call_user_func($this->viewLoader, $viewName);
        $result = call_user_func($view, $params);
        if (!is_string($result)) {
            throw new \UnexpectedValueException("The result of view '$viewName' is not a string");
        }
        return $result;
    }

    public function render($view, array $params = array())
    {
        if ($view === null) {
            throw new \InvalidArgumentException("The provided view identifier is null");
        }
        $result = &$params[static::CONTENT_PARAMETER_NAME];
        foreach (array_reverse((array) $view) as $component) {
            $result = $this->applyView($component, $params);
        }
        return new Response($result);
    }
}
